<template>
  <div>
    <el-row :gutter="15">
      <el-form ref="elForm" :model="dataForm" :rules="dataRule" size="small" label-width="100px" label-position="right"
        :disabled="setting.readonly">
        <template v-if="!loading && formOperates">
          <el-col :span="24">
            <el-form-item label-width="0">
              <groupTitle content-position="left" :closable="false" content="基础信息"></groupTitle>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="judgeShow('image')">
            <el-form-item label="商品封面" prop="image">
              <JNPF-UploadImg v-model="dataForm.image" :fileSize="5" :disabled="judgeWrite('image')" sizeUnit="MB":limit="5" :detailed="dataForm.image == 1" @change="uploadImgChange">
              </JNPF-UploadImg>
              <div class="img_text">商品图片大小不能超过5M,总数量不能超过5张（第一张为商品主图） 图片最佳大小212 x 212</div>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="dataForm.name" placeholder="请输入商品名称" :maxlength="20" :disabled="judgeWrite('name')"
                clearable :style='{"width":"100%"}'>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="商品分类" prop="goodsTypeId">
              <JNPF-TreeSelect v-model="dataForm.goodsTypeId" :disabled="judgeWrite('goodstypeid')" :options="treeData" :props="parentIdProps" :defaultExpandAll="false" placeholder="选择上级分类" />
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="商品单位" prop="goodsUnitId">
              <el-select v-model="dataForm.goodsUnitId" placeholder="请选择商品单位" :disabled="judgeWrite('goodsunitid')" :popper-append-to-body="false"
                clearable :style='{"width":"100%"}'>
                <el-option v-for="(item, index) in goodsUnitIdOptions" :key="index" :label="item.fullName"
                  :value="item.id" ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="商品状态" prop="showMark">
              <el-select v-model="dataForm.showMark" :popper-append-to-body="false" placeholder="请选择商品状态"  clearable :disabled="judgeWrite('showmark')"
                :style='{"width":"100%"}'>
                <el-option v-for="(item, index) in showmarkOptions" :key="index" :label="item.fullName" :value="item.id"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="商品价格(元)" prop="price">
              <el-input v-model="dataForm.price" placeholder="请输入商品价格" @input="changeNum($event,'price')" :maxlength="10" type="text" :disabled="judgeWrite('price')"
                clearable :style='{"width":"100%"}'>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label-width="0">
              <groupTitle content-position="left" :closable="false" content="商品规格">
              </groupTitle>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="formOperates">
            <el-form-item label-width="0">
              <el-table :data="dataForm.goodsSpecList" size='mini'>
                <el-table-column type="index" width="50" label="序号" align="center" />
                <el-table-column prop="specImg" label="规格图片" v-if="judgeShow('goodsspecList-specimg')">
                  <template slot="header" v-if="judgeRequired('goodsspecList-specimg')">
                    <span class="required-sign">*</span>规格图片
                  </template>
                  <template slot-scope="scope">
                    <JNPF-UploadImg v-model="scope.row.specImg" :fileSize="5" :disabled="judgeWrite('goodsspecList-specimg')"
                      sizeUnit="MB" :limit="1" :detailed="scope.row.specImg && scope.row.specImg.length == 1">
                    </JNPF-UploadImg>
                  </template>
                </el-table-column>
                <el-table-column prop="specName" label="规格名称" v-if="judgeShow('goodsspecList-specname')">
                  <template slot="header" v-if="judgeRequired('goodsspecList-specname')">
                    <span class="required-sign">*</span>规格名称
                  </template>
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.specName" placeholder="请输入规格名称" :maxlength="20" :disabled="judgeWrite('goodsspecList-specname')"
                      clearable :style='{"width":"100%"}'>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="costPrice" label="成本价" v-if="judgeShow('goodsspecList-costprice')">
                  <template slot="header" v-if="judgeRequired('goodsspecList-costprice')">
                    <span class="required-sign">*</span>成本价
                  </template>
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.costPrice" placeholder="请输入成本价" type="text" :maxlength="10" @input="changeNum($event,'costPrice',scope.$index)" :disabled="judgeWrite('goodsspecList-costprice')"
                      clearable :style='{"width":"100%"}'>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="retailPrice" label="零售价" v-if="judgeShow('goodsspecList-retailprice')">
                  <template slot="header" v-if="judgeRequired('goodsspecList-retailprice')">
                    <span class="required-sign">*</span>零售价
                  </template>
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.retailPrice" placeholder="请输入零售价" :maxlength="10" type="text" @input="changeNum($event,'retailPrice',scope.$index)"
                     :disabled="judgeWrite('goodsspecList-retailprice')" clearable :style='{"width":"100%"}'>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="stockNum" label="库存数量" v-if="judgeShow('goodsspecList-stocknum')">
                  <template slot="header" v-if="judgeRequired('goodsspecList-stocknum')">
                    <span class="required-sign">*</span>库存数量
                  </template>
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.stockNum" oninput="value=value.replace(/[^0-9]/g,'').replace(/^[0]+/, '')" placeholder="请输入库存数量" :maxlength="10" type="text"
                     :disabled="judgeWrite('goodsspecList-stocknum')" clearable :style='{"width":"100%"}'>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="50" v-if="!setting.readonly && !judgeWrite('description')">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" class="JNPF-table-delBtn"
                      @click="delgoodsspecList(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="table-actions" @click="addgoodsspecList()" v-if="!judgeWrite('description')">
                <el-button type="text" icon="el-icon-plus">添加</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label-width="0">
              <groupTitle content-position="left" :closable="false" content="商品详情">
              </groupTitle>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="judgeShow('description')">
            <el-form-item prop="description">
              <JNPF-Quill v-model="dataForm.description" placeholder="请输入商品详情" :disabled="judgeWrite('description')">
              </JNPF-Quill>
            </el-form-item>
          </el-col>
        </template>
      </el-form>
    </el-row>
    <UserBox v-if="userBoxVisible" ref="userBox" @submit="submit" />
  </div>
</template>
<script>
  import request from '@/utils/request'
  import { getGoodsTypeTree } from '@/api/asso/goods/category'
  import { getDataInterfaceRes } from '@/api/systemData/dataInterface'
  import {getDictionaryDataSelector } from '@/api/systemData/dictionary'
  export default {
    components: {},
    props: [],
    data() {
      return {
        visible: false,
        loading: false,
        setting: {},
        eventType: '',
        userBoxVisible: false,
        currTableConf: {},
        addTableConf: {
          goodsSpecList: {
            "popupType": "dialog",
            "hasPage": true,
            "popupTitle": "选择数据",
            "pageSize": 20,
            "columnOptions": [],
            "interfaceId": "",
            "interfaceName": "",
            "relationOptions": [],
            "templateJson": [],
            "popupWidth": "800px"
          },
        },
        tableRows: {
          goodsSpecList: {
            specImg: [],
            specName: '',
            costPrice: '',
            retailPrice: '',
            stockNum: '',
            enabledmark: undefined
          }
        },
        dataForm: {
          id: '',
          flowId: '',
          status: 1,
          freeapproveruserid: '',
          flowUrgent: 1,
          image: [],
          name: undefined,
          goodsTypeId: undefined,
          goodsUnitId: undefined,
          showMark: undefined,
          price: undefined,
          goodScode: undefined,
          creatorTime: undefined,
          description: undefined,
          goodsSpecList: [],
        },
        tableRequiredData: {},
        dataRule: {
          image: [{
            required: true,
            message: '请至少选择一个',
            trigger: 'change'
          }, ],
          name: [{
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }, ],
          goodsTypeId: [{
            required: true,
            message: '请选择商品分类',
            trigger: 'change'
          }, ],
          goodsUnitId: [{
            required: true,
            message: '请选择商品单位',
            trigger: 'change'
          }, ],
          showMark: [{
            required: true,
            message: '请选择商品状态',
            trigger: 'change'
          }, ],
          price: [{
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          }, ],
          specName: [{
            required: true,
            message: '请输入规格名称',
            trigger: 'blur'
          }, ],
          retailPrice: [{
              required: true,
              message: '请输入零售价',
              trigger: 'blur'
            },
            {
              pattern: /^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$/,
              message: '请输入正确的零售价',
              trigger: 'blur'
            },
          ],
          stockNum: [{
              required: true,
              message: '请输入库存数量',
              trigger: 'blur'
            },
            {
              pattern: /^\d+$/,
              message: '请输入正确的数字',
              trigger: 'blur'
            },
          ],

        },
        goodsTypeIdOptions: [],
        goodsUnitIdOptions: [{
          "fullName": "吨",
          "id": "1"
        }, {
          "fullName": "千克",
          "id": "2"
        }],
        showmarkOptions: [{
          "fullName": "上架",
          "id": 1
        }, {
          "fullName": "下架",
          "id": 0
        }],
        treeData: [],
        parentIdProps: {
          value: 'id',             // ID字段名
          label: 'name',       // 显示名称
          children: 'children',    // 子级字段名
          disabled: false
        }
      }
    },
    computed: {
      formOperates() {
        return this.setting.formOperates
      }
    },
    watch: {},
    created() {
      this.getgoodsUnitIdOptions();
    },
    mounted() {},
    methods: {
      changeNum(e, col, i){
        if(col == 'price'){
          this.dataForm.price = this.dataForm.price
            .replace(/[^\d^\.]+/g, '')
            .replace(/^0+(\d)/, '$1')
            .replace(/^\./, '0.')
            .match(/^\d*(\.?\d{0,2})/g)[0] || ''
        }
        if(col == 'costPrice'){
          this.dataForm.goodsSpecList[i].costPrice = this.dataForm.goodsSpecList[i].costPrice
            .replace(/[^\d^\.]+/g, '')
            .replace(/^0+(\d)/, '$1')
            .replace(/^\./, '0.')
            .match(/^\d*(\.?\d{0,2})/g)[0] || ''
        }
        if(col == 'retailPrice'){
          this.dataForm.goodsSpecList[i].retailPrice = this.dataForm.goodsSpecList[i].retailPrice
            .replace(/[^\d^\.]+/g, '')
            .replace(/^0+(\d)/, '$1')
            .replace(/^\./, '0.')
            .match(/^\d*(\.?\d{0,2})/g)[0] || ''
        }
      },
      getTreeView() {
        getGoodsTypeTree().then(res => {
          if(res.code == 200){
            let topItem = {
              name: "商品分类",
              hasChildren: true,
              id: "-1",
              children: JSON.parse(JSON.stringify(res.data.list))
            }
            this.treeData = [topItem]
          }
        })
      },
      judgeShow(id) {
        if (!this.setting.formOperates || !this.setting.formOperates.length) return true
        let arr = this.setting.formOperates.filter(o => o.id === id) || []
        if (!arr.length) return true
        let item = arr[0]
        return item.read
      },
      judgeWrite(id) {
        if (!this.setting.formOperates || !this.setting.formOperates.length) return false
        let arr = this.setting.formOperates.filter(o => o.id === id) || []
        if (!arr.length) return true
        let item = arr[0]
        return !item.write
      },
      getgoodsUnitIdOptions() {
        getDictionaryDataSelector('367422992470246661').then(res => {
          this.goodsUnitIdOptions = res.data.list
        })
      },
      goBack() {
        this.$emit('refresh')
      },
      init(data) {
        this.dataForm.id = data.id || "";
        this.setting = data;
        this.visible = true;
        this.updateDataRule()
        this.$nextTick(() => {
          this.getTreeView();
          this.$refs['elForm'].resetFields();
          if (this.dataForm.id) {
            this.loading = true
            request({
              url: '/api/zgyf/Goods/' + this.dataForm.id,
              method: 'get'
            }).then(res => {
              this.dataInfo(res.data)
              this.loading = false
            })
          }
          this.$emit('setPageLoad')
        })
        this.$store.commit('generator/UPDATE_RELATION_DATA', {})
      },
      updateDataRule() {
        let newRules = {}
        for (let i = 0; i < this.setting.formOperates.length; i++) {
          const item = this.setting.formOperates[i]
          if (!item.id.includes('-')) {
            const newRulesItem = {
              required: item.required,
              message: item.name + '不能为空',
              trigger: item.trigger || 'blur'
            }
            if (!this.dataRule.hasOwnProperty(item.id)) {
              if (item.required) this.$set(newRules, item.id, [newRulesItem])
            } else {
              let withoutRequiredItem = true
              for (let i = 0; i < this.dataRule[item.id].length; i++) {
                if (this.dataRule[item.id][i].hasOwnProperty('required')) {
                  this.dataRule[item.id][i].required = item.required
                  withoutRequiredItem = false
                }
              }
              if (withoutRequiredItem && item.required) this.dataRule[item.id].push(newRulesItem)
            }
          } else {
            let key = item.id.split('-')[0]
            let newId = item.id.split('-')[1]
            let newItem = {
              ...item,
              id: newId
            }
            if (!this.tableRequiredData.hasOwnProperty(key)) {
              this.$set(this.tableRequiredData, key, [newItem])
            } else {
              this.tableRequiredData[key].push(newItem)
            }
          }
        }
        this.dataRule = {
          ...this.dataRule,
          ...newRules
        }
      },
      exist() {
        let isOk = true
        for (let key in this.tableRequiredData) {
          if (this.dataForm[key] && Array.isArray(this.dataForm[key])) {
            for (let i = 0; i < this.dataForm[key].length; i++) {
              let item = this.dataForm[key][i]
              inner: for (let id in item) {
                let arr = this.tableRequiredData[key].filter(o => o.id === id) || []
                if (!arr.length) continue inner
                if (arr[0].required) {
                  let msg = `${arr[0].name}不能为空`
                  let boo = true
                  if (arr[0].dataType === 'array') {
                    boo = !this.jnpf.isEmptyArray(item[id])
                  } else {
                    boo = !this.jnpf.isEmpty(item[id])
                  }
                  if (!boo) {
                    this.$message({
                      message: msg,
                      type: 'error',
                      duration: 1000
                    })
                    isOk = false
                    break
                  }
                }
              }
            }
          }
        }
        return isOk
      },
      judgeRequired(id) {
        if (!this.formOperates || !this.formOperates.length) return false
        let arr = this.formOperates.filter(o => o.id === id) || []
        if (!arr.length) return false
        let item = arr[0]
        return item.required
      },
      // 表单提交
      dataFormSubmit(eventType, flowUrgent) {
        if(this.dataForm.price == 0){
          this.$message({
            message: '商品价格不能为0',
            type: 'error',
            duration: 1000
          })
          return
        }
        this.$refs['elForm'].validate((valid) => {
          if (valid) {
            if(this.dataForm.goodsTypeId == '-1'){
              this.$message({
                message: '顶级分类下不能新增商品！',
                type: 'error',
                duration: 1000
              })
              return
            }
            if(this.dataForm.goodsSpecList.length == 0){
              this.$message({
                message: '至少填写一条商品规格！',
                type: 'error',
                duration: 1000
              })
              return
            }
            let flag = false
            this.dataForm.goodsSpecList.forEach((item) => {
              if(item.specName == undefined || item.specName == null || item.specName == ''){
                this.$message({
                  message: '商品规格规格名称必填！',
                  type: 'error',
                  duration: 1000
                })
                flag = true
              }
              if(item.costPrice == undefined || item.costPrice == null || item.costPrice == ''){
                this.$message({
                  message: '商品规格成本价必填！',
                  type: 'error',
                  duration: 1000
                })
                flag = true
              }
              if(item.retailPrice == undefined || item.retailPrice == null || item.retailPrice == ''){
                this.$message({
                  message: '商品规格零售价必填！',
                  type: 'error',
                  duration: 1000
                })
                flag = true
              }
              if(item.stockNum == undefined || item.stockNum == null || item.stockNum == ''){
                this.$message({
                  message: '商品规格库存数量必填！',
                  type: 'error',
                  duration: 1000
                })
                flag = true
              }
              if(item.costPrice == 0){
                this.$message({
                  message: '商品规格成本价不能为0！',
                  type: 'error',
                  duration: 1000
                })
                flag = true
              }
              if(item.retailPrice == 0){
                this.$message({
                  message: '商品规格零售价不能为0！',
                  type: 'error',
                  duration: 1000
                })
                flag = true
              }
              if(item.stockNum == 0){
                this.$message({
                  message: '商品规格库存数量不能为0！',
                  type: 'error',
                  duration: 1000
                })
                flag = true
              }
            })
            if(!flag){
              if (this.exist && !this.exist()) return
              if (eventType === 'audit' || eventType === 'reject') {
                this.$emit('eventReceiver', this.dataForm, eventType)
                return
              }
              this.dataForm.status = eventType === 'submit' ? 0 : 1
              this.dataForm.flowId = this.setting.flowId
              this.dataForm.flowUrgent = flowUrgent
              this.eventType = eventType
              if (this.eventType === 'submit') {
                this.$confirm('您确定要提交当前流程吗, 是否继续?', '提示', {
                  type: 'warning'
                }).then(() => {
                  this.request()
                }).catch(() => {});
              } else {
                this.request()
              }
            }
          }
        })
      },
      request() {
        var _data = this.dataList()
        this.dataForm.price = Number(this.dataForm.price)
        if (!this.dataForm.id) {
          request({
            url: '/api/zgyf/Goods',
            method: 'post',
            data: _data
          }).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.visible = false
                this.$emit('close', true)
              }
            })
          })
        } else {
          request({
            url: '/api/zgyf/Goods/' + this.dataForm.id,
            method: 'PUT',
            data: _data
          }).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.visible = false
                this.$emit('close', true)
              }
            })
          })
        }
      },
      addgoodsspecList() {
        let item = {
          specImg: undefined,
          specName: undefined,
          costPrice: undefined,
          retailPrice: undefined,
          stockNum: undefined,
        }
        this.dataForm.goodsSpecList.push(item)
      },
      delgoodsspecList(index) {
        this.dataForm.goodsSpecList.splice(index, 1);
      },
      openSelectDialog(key) {
        this.currTableConf = this.addTableConf[key]
        this.currVmodel = key
        this.selectDialogVisible = true
        this.$nextTick(() => {
          this.$refs.selectDialog.init()
        })
      },
      addForSelect(data) {
        for (let i = 0; i < data.length; i++) {
          let item = {
            ...this.tableRows[this.currVmodel],
            ...data[i]
          }
          this.dataForm[this.currVmodel].push(item)
        }
      },
      dataList() {
        var _data = JSON.parse(JSON.stringify(this.dataForm));
        _data.image = JSON.stringify(_data.image)
        for (let i = 0; i < _data.goodsSpecList.length; i++) {
          var _list = _data.goodsSpecList[i];
          if(_list.specImg){
            _list.specImg = JSON.stringify(_list.specImg)
          }else{
            _list.specImg = undefined
          }
        }
        return _data;
      },
      dataInfo(dataAll) {
        let _dataAll = dataAll
        _dataAll.image = JSON.parse(_dataAll.image)
        for (let i = 0; i < _dataAll.goodsSpecList.length; i++) {
          var _list = _dataAll.goodsSpecList[i];
          if(_list.specImg){
            _list.specImg = JSON.parse(_list.specImg)
          }else{
            _list.specImg = undefined
          }
        }
        this.dataForm = _dataAll
      },
      uploadImgChange(e){
        // 上传成功后，手动验证一次表单
        this.$refs['elForm'].validateField('image')
      },
    },
  }
</script>
<style lang="scss" scoped>
  .img_text {
    color: red;
  }
</style>
